package com.cloud.socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

//@Component
public class SocketServer {

    private static final Logger LOG = LoggerFactory.getLogger(SocketServer.class.getName());

    @Value("${sso.check.userid}")
    private Integer userId;

    @Value("${sso.check.tenantcode}")
    private String tenantCode;

    @Value("${sso.check.token}")
    private String token;


    public SocketServer() {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                60L, TimeUnit.SECONDS,
                new SynchronousQueue<Runnable>());
        // 用新线程维护SocketServer, 解决项目请求阻塞问题

        Thread socketServerThread = new Thread(() -> {
            Socket socket = null;
            try {
                ServerSocket serverSocket = new ServerSocket(6666);
                LOG.info("Socket服务端已启动,正在监听: {}端口", 6666);
                // 服务端监听
                while (true) {
                    socket = serverSocket.accept();
                    // 服务端对每个新的TCP请求都会创建新的线程去维护TCP通道
                    executor.execute(new OAMsgTask(userId, tenantCode, token, socket));
                }
            } catch (IOException e) {
                LOG.error(e.getMessage());
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    LOG.error("处理OA请求的Socket服务端关闭失败!");
                }
            }
        });
        socketServerThread.setDaemon(true);
        socketServerThread.start();
    }
}